package archsw0904.controller.shopping.order;

import java.util.ArrayList;
import java.util.Map;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import archsw0904.model.Book;
import archsw0904.model.OrderStatus;
import archsw0904.model.OrderedCopies;
import archsw0904.model.Orders;


@Stateless
public class OrderRollbackBean implements OrderRollBackBeanLocal {

	@PersistenceContext
	EntityManager em;
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void rollBackOrder(Integer orderId) throws OrderException {
		
		// Ordine esistente
		Query q = em.createQuery("SELECT OBJECT(obj) FROM Orders obj WHERE obj.id = " + orderId.toString());
		Orders order =  (Orders) q.getSingleResult();
		if ( order == null ) {
			throw new OrderException ( OrderExceptionType.OrderNotPresent ) ;
		}
		
		ArrayList<OrderedCopies> oc = new ArrayList<OrderedCopies>() ; 
		ArrayList<Book> b = new ArrayList<Book>() ; 
		
		Map<Book,OrderedCopies> mapList = order.getBookList() ;
		
		for ( Book book : mapList.keySet() ) {
			// ripristino numero di copie available del libro
			
			// correttezza del numero di copie rilasciate
			// magazzino
			if ( book.getCopiesInStockroom().intValue() < (book.getAvailableCopies().intValue() + mapList.get(book).getNumberOfCopies().intValue()) ) 
				throw new OrderException ( OrderExceptionType.TooManyCopies ) ;
					
			// aggiornamento copie nel libro		
			book.addAvailableCopies(mapList.get(book).getNumberOfCopies()) ;

			em.persist(book) ;
			
			// rimozione del numero di copie dalla persistenza
			System.out.println("PRE GET MAP") ;
			oc.add(mapList.get(book)) ;
			b.add(book);
			System.out.println("POST GET MAP") ;

		}

		System.out.println("PRE RIMOZIONE ARRAY BOOK") ;
		while ( !b.isEmpty() ) { 
			System.out.println("RIMUOVO " + b.get(0).getId()) ;
			mapList.remove(b.remove(0)) ; 
			}
		
		System.out.println("PRE RIMOZIONE ARRAY COPIES") ;
		while ( !oc.isEmpty() ) { 
			System.out.println("RIMUOVO " + oc.get(0).getId().toString()) ;
			em.remove(oc.remove(0)) ; 
			}
		
		order.setStatus(OrderStatus.Cancelled) ;
		
		em.persist(order);
	}

}
